package com.jingbit.ai.sound;

import android.media.MediaRecorder;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SoundRecorder {
    static MediaRecorder mRecorder;
    static boolean isRecording;

    public static void startRecording(String fileName) {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(newFileName(fileName));
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
            isRecording = true;
        } catch (IOException e) {
            Log.e("jingbit", "prepare() failed");
            isRecording = false;
        }
        mRecorder.start();
    }

    public static void stopRecording() {
        isRecording = false;
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }

    public static String newFileName(String fileName) {
        String mFileName = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        if (TextUtils.isEmpty(fileName)) {
            String s = new SimpleDateFormat("yyyy-MM-dd hhmmss")
                    .format(new Date());
            return mFileName += "/rcd_" + s + ".wav";
        }
        return mFileName += fileName;
    }
}
